//
//  RecordTableViewController.swift
//  NoteBook
//
//  Created by iOS Developer on 2017/4/25.
//  Copyright © 2017年 sunsheen. All rights reserved.
//

import UIKit
import CoreData
class RecordTableViewController: UITableViewController,UIPopoverPresentationControllerDelegate, UINavigationControllerDelegate {
    var records = [Record]()
    override func viewDidLoad() {
        super.viewDidLoad()
        records = AppDelegate.currentWriter?.records?.allObjects as! [Record]
        refreshControl = UIRefreshControl()
        refreshControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
        refreshControl!.addTarget(self, action: #selector(refreshList(_:)), for: .valueChanged)
    }
    
    func refreshList(_ refresh: UIRefreshControl){
        if refresh.isRefreshing {
            records = AppDelegate.currentWriter?.records?.allObjects as! [Record]
            tableView.reloadData()
            refresh.endRefreshing()
        }
    }
    
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        if records.count > 0 {
            tableView.backgroundView = .none
            tableView.separatorStyle = .singleLine
            return 1
        } else {
            let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.bounds.size.width, height: view.bounds.size.height))
            messageLabel.text = "还没有开始写日记哦.\n点击右上角+新建一个."
            messageLabel.textColor = .darkGray
            messageLabel.numberOfLines = 0
            messageLabel.textAlignment = .center
            
            tableView.backgroundView = messageLabel;
            tableView.separatorStyle = .none;
            return 0
        }
    }   
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return records.count
    }   
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "titleCell", for: indexPath)
        let tempRecord = records[indexPath.row]
        cell.textLabel?.text = tempRecord.title
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        cell.textLabel?.textColor = tempRecord.titleColor as! UIColor

        return cell
    }
    @IBAction func createNewRecord(_ sender: Any) {
        let alert = UIAlertController(title: "名字", message: nil, preferredStyle: .alert)
        alert.addTextField{ tf in
            tf.placeholder = "给个名字吧"
        }
        alert.addAction(UIAlertAction(title: "确定", style: .default) { _ in
            self.performSegue(withIdentifier: "newRecord", sender: alert.textFields?.first?.text?.trimmingCharacters(in: .whitespaces))
        })
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        present(alert, animated: true)
    }
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    // Override to support conditional editing of the table view.

    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let setColor = UITableViewRowAction(style: .normal, title: "颜色") { (ra, indexPath) in
            if let pop = self.storyboard?.instantiateViewController(withIdentifier: "colorChoose") as? ColorChooseViewController{
                pop.modalPresentationStyle = .popover
                pop.popoverPresentationController?.delegate = self
                pop.popoverPresentationController?.sourceView = tableView.cellForRow(at: indexPath)
                pop.popoverPresentationController?.sourceRect = tableView.cellForRow(at: indexPath)!.bounds
                pop.preferredContentSize = CGSize(width: pop.preferredContentSize.width, height: 50)
                pop.colorDelegate = self
                pop.indexPath = indexPath
                self.present(pop, animated: true)
            }
        }
        let delete = UITableViewRowAction(style: .default, title: "删 除") { (ra, indexPath) in
            // Delete the row from the data source
            AppDelegate.viewContext.delete(self.records[indexPath.row])
            self.records.remove(at: indexPath.row)
            if self.records.count < 1 {
                tableView.reloadData()
            }else {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            try? AppDelegate.viewContext.save()
        }
        let changeTitle = UITableViewRowAction(style: .destructive, title: "标题") { (ra, indexPath) in
            let alert = UIAlertController(title: "标题", message: nil, preferredStyle: .alert)
            alert.addTextField{ tf in
                tf.text = self.records[indexPath.row].title
                tf.clearButtonMode = .always
            }
            alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { _ in
                var keyValue: String = alert.textFields?.first?.text ?? ""
                keyValue = keyValue.trimmingCharacters(in: .whitespaces)
                if !keyValue.isEmpty {
                    self.records[indexPath.row].title = keyValue
                    try? AppDelegate.viewContext.save()                    
                }
                self.tableView.reloadRows(at: [indexPath], with: .automatic)
            }))
            self.present(alert, animated: true)
        }
        changeTitle.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)

        return [delete, changeTitle, setColor]
    }
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let identifier = segue.identifier else {
            return
        }
        switch identifier {
        case "newRecord":
            // should choose color and write title
            let newRecord = Record(context: AppDelegate.viewContext)
            AppDelegate.currentWriter?.addToRecords(newRecord)
            newRecord.date = Date() as NSDate
            let title = sender as! String
            newRecord.title = title.isEmpty ? Date().debugDescription : title
            newRecord.titleColor = UIColor.black
            (segue.destination as! ContentViewController).belongRecord = newRecord
            records = AppDelegate.currentWriter?.records?.allObjects as! [Record]
            tableView.reloadData()
        case "oldRecord":
            if let index = tableView.indexPathForSelectedRow {
                (segue.destination as! ContentViewController).belongRecord = records[index.row]
            }
        default: break
        }
    }
}
extension RecordTableViewController: CellColorDelegate {
    func setColor4Cell(at indexPath: IndexPath, with color: UIColor) {
        records[indexPath.row].titleColor = color
        try? AppDelegate.viewContext.save()
        tableView.reloadRows(at: [indexPath], with: .automatic)
    }
}
